package com.mall.shopping.services;

import com.mall.shopping.IProductCateService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ProductCateConverter;
import com.mall.shopping.dal.entitys.ItemCat;
import com.mall.shopping.dal.persistence.ItemCatMapper;
import com.mall.shopping.dto.AllProductCateRequest;
import com.mall.shopping.dto.AllProductCateResponse;
import com.mall.shopping.dto.ProductCateDto;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Service
@Slf4j
public class ProductCateServiceImpl implements IProductCateService {

    @Autowired
    ItemCatMapper cateMapper;

    @Autowired
    ProductCateConverter cateConverter;

    @Override
    public AllProductCateResponse getAllProductCate(AllProductCateRequest request) {
        request.requestCheck();

        AllProductCateResponse allProductCateResponse = new AllProductCateResponse();
        allProductCateResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        allProductCateResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        Example itemCatExample = new Example(ItemCat.class);
        String orderCol = "sort_order";
        String orderDir = "asc";
        if(request.getSort().equals("1")){
            orderCol="sort_order";
            orderDir="asc";
        }else if(request.getSort().equals("-1")){
            orderCol="sort_order";
            orderDir="desc";
        }
        List<ProductCateDto> productCateDtos = null;
        try {
            itemCatExample.setOrderByClause(orderCol + " " + orderDir);
            List<ItemCat> itemCats = cateMapper.selectByExample(itemCatExample);
            productCateDtos = cateConverter.items2Dto(itemCats);
        } catch (Exception e) {
            log.error("ProductCateServiceImpl.getAllProductCate Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(allProductCateResponse, e);
        }
        allProductCateResponse.setProductCateDtoList(productCateDtos);
        return allProductCateResponse;
    }
}
